package com.lagou.springbootframework;

import com.lagou.springbootframework.MyWebApplicationInitializer;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.lang.Nullable;
import org.springframework.util.ReflectionUtils;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import java.lang.reflect.Modifier;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 *
 * 初始化spring servlet容器
 * 注意，这个地方的@HandlesTypes注解包含的自己的定义的
 * SpringServlet容器
 */
@HandlesTypes({MyWebApplicationInitializer.class})
public class MySpringServletContainerInitializer implements ServletContainerInitializer {


    public void onStartup(@Nullable Set<Class<?>> MyWebApplicationInitializer, ServletContext servletContext) throws ServletException {
        System.out.println("laile.....123");
        List<MyWebApplicationInitializer> initializers = new LinkedList();
        System.out.println("初始化容器。。。");
        Iterator var4;
        if (MyWebApplicationInitializer != null) {
            var4 = MyWebApplicationInitializer.iterator();

            while(var4.hasNext()) {
                Class<?> waiClass = (Class)var4.next();
                if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) && MyWebApplicationInitializer.class.isAssignableFrom(waiClass)) {
                    try {
                        initializers.add((MyWebApplicationInitializer) ReflectionUtils.accessibleConstructor(waiClass, new Class[0]).newInstance());
                    } catch (Throwable var7) {
                        throw new ServletException("Failed to instantiate WebApplicationInitializer class", var7);
                    }
                }
            }
        }

        if (initializers.isEmpty()) {
            servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
        } else {
            servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
            AnnotationAwareOrderComparator.sort(initializers);
            var4 = initializers.iterator();

            while(var4.hasNext()) {
                //调用自己写的web初始化容器
                MyWebApplicationInitializer initializer = (MyWebApplicationInitializer)var4.next();
                initializer.onStartup(servletContext);
            }

        }
    }
}
